package service;


import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static util.DBUtil.conn;

// 日志服务类
public class LogService {

    public static void logAction(String username, String action) {
        try(PreparedStatement ptmt=conn.prepareStatement("INSERT INTO logs (action_time,user_name, action) VALUES (?, ?, ?)");){
            ptmt.setTimestamp(1, Timestamp.from(Instant.now()));
            ptmt.setString(2,username);
            ptmt.setString(3,action);
            ptmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("记录日志失败: user=" + username + ", action=" + action, e);
        }
    }

    public static void printAllLogs() {
        System.out.println("\n===== 系统日志 =====");

        try (PreparedStatement ptmt = conn.prepareStatement("SELECT action_time, user_name, action FROM logs");
             ResultSet rs = ptmt.executeQuery()) {

            boolean hasLogs = false;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            while (rs.next()) {
                hasLogs = true;
                String timeStr = rs.getString("action_time");
                // 直接使用字符串时间戳转换为Date对象
                long timestamp = Long.parseLong(timeStr);
                String formattedTime = sdf.format(new Date(timestamp));  // 修正这里
                System.out.printf("[%s] %s: %s%n",
                        formattedTime,
                        rs.getString("user_name"),
                        rs.getString("action"));
            }

            if (!hasLogs) {
                System.out.println("暂无日志记录");
            }
        } catch (SQLException e) {
            throw new RuntimeException("打印日志失败: " + e.getMessage(), e);
        }
        System.out.println("===================");
    }
}
